# -*- coding:utf-8 -*-
import os
import sys
sys.path.append("../")

from infer import Inference
from features.string_match import StringMatcher
from features.tf_idf import TFIDF

FEATURES = [
    "BiLSTM",
    "CNN",
    "MultiChannel",
    "TF-IDF",
    "lcs_word",
    "lcs_char",
    "edit_distance_word",
    "edit_distance_char"
]


def get_feature2idx():
    feat2idx = dict()
    for idx, feat_name in enumerate(FEATURES):
        feat2idx[feat_name] = idx
    return feat2idx


class FeatureManager(object):
    def __init__(self, deep_infer_config, base_cwd="../"):
        cur_path = os.getcwd()
        os.chdir(base_cwd)
        self.deep_inference = Inference(deep_infer_config)
        self.string_matcher = StringMatcher()
        self.tf_idf = TFIDF("./lib/idf.dict")

        os.chdir(cur_path)
        self.feat2idx = get_feature2idx()
        pass

    def get_feature_idx(self, feat_name):
        return self.feat2idx[feat_name] if feat_name in self.feat2idx else -1

    @property
    def features(self):
        return FEATURES

    @property
    def feat_size(self):
        return len(self.feat2idx)

    def predict(self, query: list, candidate: list):
        feat_vector = [0.0 for _ in range(self.feat_size)]

        deep_result = self.deep_inference.infer(query, candidate)
        for key in deep_result:
            if key in self.feat2idx:
                feat_vector[self.feat2idx[key]] = deep_result[key]

        tf_idf_score = self.tf_idf.score(query, candidate)
        feat_vector[self.feat2idx["TF-IDF"]] = tf_idf_score

        str_result = self.string_matcher.match(query, candidate)
        for key in str_result:
            if key in self.feat2idx:
                feat_vector[self.feat2idx[key]] = str_result[key]
        return feat_vector
